package 基础篇.工具类.ThreadLocal;

/**
 * 同步机制是为了同步多个线程对相同资源的并发访问，而threadLocal将需要并发访问的资源复制多份，每个线程都拥有资源资源的副本
 */
public class ThreadLocalDemo {
    private ThreadLocal<String> name=new ThreadLocal<>();

    public ThreadLocalDemo(String str) {
        name.set(str);
    }

    public String getName(){
        return name.get();
    }

    public void setName(String str){
        name.set(str);
    }
}

class MyTest extends Thread{
    private  ThreadLocalDemo threadLocalDemo;
    public MyTest(ThreadLocalDemo threadLocalDemo, String name){
        super(name);
        this.threadLocalDemo=threadLocalDemo;
    }

    public void run(){
        for(int i=0;i<10;i++){
            if(i==6){
                threadLocalDemo.setName(getName());
            }
                System.out.println(threadLocalDemo.getName()+" i:"+i);
        }
    }
}

class ThreadLocalTest{
    public static void main(String[] args) {
        ThreadLocalDemo threadLocalDemo=new ThreadLocalDemo("init name");
        new MyTest(threadLocalDemo,"t1").start();
        new MyTest(threadLocalDemo,"t2").start();
    }
}
